<?php

namespace app\v1\controller;

use app\common\model\Config;
use app\common\model\Payment;
use app\common\model\UserBalanceLog;
use helper\util\Encrypt;

class PaymentController extends ApiBaseController
{
    /**
     * @OA\Post(path="/payment/create",tags={"支付"},summary="创建交易",
     *   @OA\Parameter(name="authorization", in="header", description="AppSecret", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="应用ID", property="appid", type="string"),
     *           @OA\Property(description="商户订单号", property="out_trade_no", type="string"),
     *           @OA\Property(description="订单标题", property="subject", type="string"),
     *           @OA\Property(description="订单金额", property="amount", type="string"),
     *           @OA\Property(description="同步通知地址", property="callback_url", type="string"),
     *           @OA\Property(description="异步通知地址", property="notify_url", type="string"),
     *           @OA\Property(description="场景类型: page, wap", property="scene_type", type="string", default="page"),
     *           @OA\Property(description="订单失效时长", property="expire_time", type="integer", default="600"),
     *           @OA\Property(description="商品列表信息", property="goods_detail", type="json"),
     *           required={"appid","out_trade_no","subject","amount","notify_url","scene_type"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function create()
    {
        $param = $this->request->param();
        $log = UserBalanceLog::create([
            'user_id'      => $this->user_id,
            'out_trade_no' => $param['out_trade_no'],
            'subject'      => $param['subject'],
            'amount'       => $param['amount'],
            'callback_url' => $param['callback_url'],
            'notify_url'   => $param['notify_url'],
            'type'         => 5
        ]);
        $plat = $param['scene_type'] == 'page' ? 'page' : 'wap';
        $param['expire_time'] = $param['expire_time'] ?? 600;
        $param['expire_time'] = time() + $param['expire_time'];
        $auth = urlencode(Encrypt::encrypt(json_encode($param), 'DES-EDE3', 'payment'));
        $info = [
            'order_id'    => $log->id,
            'expire_time' => $param['expire_time'],
            'return_url'  => $this->request->domain() . '/cashier?plat=' . $plat . '&out_trade_no=' . $param['out_trade_no'] . '&sign=' . $auth
        ];
        $this->result($info);
    }

    /**
     * @OA\Get(path="/payment/query",tags={"支付"},summary="查询交易",
     *   @OA\Parameter(name="out_trade_no", in="query", description="商户订单号", @OA\Schema(type="string")),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function query()
    {
        $out_trade_no = $this->request->param('out_trade_no');
        $data = UserBalanceLog::where('user_id', $this->user_id)->where('out_trade_no', $out_trade_no)->find();
        $this->result(0,'获取成功', $data);
    }

    /**
     * @OA\Post(path="/payment/close",tags={"支付"},summary="关闭交易",
     *   @OA\Parameter(name="authorization", in="header", description="AppSecret", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *        @OA\Schema(
     *          @OA\Property(description="商户订单号", property="out_trade_no", type="string"),
     *          required={"out_trade_no"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function close()
    {
        $out_trade_no = $this->request->param('out_trade_no');

        //$this->result(0,'获取成功', $data);
    }

    /**
     * @OA\Post(path="/payment/refund",tags={"支付"},summary="交易退款",
     *   @OA\Parameter(name="authorization", in="header", description="AppSecret", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *        @OA\Schema(
     *           @OA\Property(description="商户订单号", property="out_trade_no", type="string"),
     *           @OA\Property(description="退款金额", property="amount", type="string"),
     *           @OA\Property(description="退款原因", property="reason", type="string"),
     *           required={"appid","out_trade_no","amount"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function refund()
    {
        //amount
    }

    /**
     * @OA\Post(path="/payment/transfer",tags={"支付"},summary="付款到账户",
     *   @OA\Parameter(name="Authorization", in="header", description="AppSecret", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="收款渠道", property="payment", type="string"),
     *           @OA\Property(description="收款账号", property="account", type="string"),
     *           @OA\Property(description="收款用户姓名", property="name", type="string"),
     *           @OA\Property(description="付款金额", property="amount", type="number"),
     *           @OA\Property(description="付款说明", property="reamrk", type="string"),
     *           required={"payment","account","name","amount"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function transfer()
    {
        $param   = $this->request->param();
        $user_id = $this->user_id;

        // 1.验证数据
        // 1.1 数据验证
        $this->validate($param, 'app\common\validate\Transfer');

        // 1.2 联表验证
        if ($param['amount'] > $this->user->balance) {
            $this->result('', "余额不足");
        }

        // 1.2.2 提现设置
        $config = Config::config('transfer');
        if ($param['amount'] < $config['min'] || $param['amount'] > $config['max']) {
            $this->result('', '最低提现金额不小于' . $config['min'] . '元');
        }
        $count = UserBalanceLog::where('type', 1)->whereDay('create_time')->count();
        if ($count > $config['count']) {
            $this->result('', '每日提现次数不超过' . $config['count'] . '次');
        }

        // 3.调用支付
        $fee = $config['rate'] > 0 ? round($param['amount'] * $config['rate'], 2) : 0;
        $amount = round($param['amount'] - $fee, 2);
        $trade_no = date('YmdHis') . random_int(1000,9999);
        $param['remark'] = $param['remark'] ?? '转账';
        $result = Payment::transfer($user_id, $param['payment'], $fee, $trade_no, $amount, $param['account'], $param['name'], $param['reamrk']);
        if ($result) {
            $this->result($result, '转账成功');
        }
        $this->result('','转账失败');
    }

    // 付款到银行卡
    public function payBank()
    {

    }
}